package rensoft.android.lang;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import static rensoft.android.lang.AndroidLang.asString;
import static rensoft.android.lang.AndroidLang.event;
import static rensoft.java.lang.Lang.info;
import static rensoft.java.lang.Lang.iterate;
import static rensoft.java.lang.Lang.map;

import rensoft.java.collections.Map;
import rensoft.java.collections.Mapped;
import rensoft.java.event.Event;
import rensoft.java.lang.Base;
import rensoft.java.lang.Run;
import rensoft.java.net.UrlBuilder;

public abstract class RequestBase extends Base implements Run {

  protected final Event<Void> eventDone = event();
  protected final Event<Void> eventFailed = event();
  protected final Event<Void> eventLoaded = event();

  private final Map<String, CharSequence> arguments = map();

  public void add(String key, Object argument) {
    arguments.put(key, String.valueOf(argument));
  }

  public Event<Void> eventDone() {
    return eventDone;
  }

  public Event<Void> eventFailed() {
    return eventFailed;
  }

  public Event<Void> eventLoaded() {
    return eventLoaded;
  }

  public UrlBuilder getUrl() {
    UrlBuilder url = new UrlBuilder(getServerUrl());
    for (Mapped<String, CharSequence> argument : iterate(arguments))
      url.add(argument.key(), argument.value());
    onUrlCreated(url);
    return url;
  }

  public void send() {
    AndroidLang.getAplication().getRequestManager().send(this);
  }

  protected String getResponseString(String url) throws Exception {
    HttpGet get = new HttpGet(url);
    info(get.getURI());
    HttpResponse response = new DefaultHttpClient().execute(get);
    String string = asString(response.getEntity().getContent());
    info("Retrived", string);
    return string;
  }

  protected abstract String getServerUrl();

  protected abstract void onUrlCreated(UrlBuilder url);
}
